package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.enums.OrderStatus;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Service("sybPayService")
public class SybPayServiceImpl extends BasePayment {




    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);
//        String qrcode = userRecipientInfo.getReceiptQrcode();
//        String qrcode_ = HttpUtils.getParam(qrcode,"userAppId");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


//
//        String url = "https://api.umvtech.com/api/payment/getUserName";
//        dataMap.put("user_code",userRecipientInfo.getPhoneNo());
//        HttpResponse priceHttpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"kiss查询用户请求","");
//        JSONObject resultObj = JSONObject.parseObject(priceHttpResponse.getDocument().body().text());
//        int resultCode = resultObj.getInteger("status");
//        String priceId = "";
//        if(resultCode==1){
//
//
//
//        }
        //https://qr.leshuazf.com/pay/qrc.do?qr=SYTD200387629


        String proxyIp =orderInfo.getProxyIp();
        logger.info("请求代理："+proxyIp);

        headerMap.put("User-Agent","Nebula AlipayDefined(nt:WIFI,ws:360|0|3.0) AliApp(AP/10.0.18.062203) AlipayClient/10.0.18.062203 Language/zh-Hans useStatusBar/true");


        logger.info("qrcode："+cookieObj.getString("userId"));

        String url ="https://www.shouyinbei.net/wap/merchant/h5pay?userAppId="+cookieObj.getString("userId")+"&qrNo=null&cokus="+orderInfo.getAliUserId()+"&payType=ZFBZF";
        logger.info("收银台HTMLurl："+url);

        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","SYB","");
        logger.info("返回的HTML:"+httpResponse.getDocument().text());

        Element priceElement =  httpResponse.getDocument().selectFirst("input[id=merchantCode]");
        String merchantCode = priceElement.val();
        logger.info("merchantCode值:"+merchantCode);


        priceElement =  httpResponse.getDocument().selectFirst("input[id=payType]");
        String payType = priceElement.val();
        logger.info("payType值:"+payType);

        String storeId = "";
        priceElement =  httpResponse.getDocument().selectFirst("input[id=storeId]");
        if(priceElement==null){
            url ="https://www.shouyinbei.net/wap/merchant/h5pay?code=&auth_code=&userAuthCode=&merchantCode="+merchantCode+"&userAppId="+cookieObj.getString("userId")+"&qrNo=null&cokus="+orderInfo.getAliUserId()+"&province="+ URLEncoder.encode(userRecipientInfo.getProvince());
            logger.info("二次收银台HTMLurl："+url);
            HttpResponse httpResponseNew = HttpUtils.httpFormGet(url,headerMap,"","SYB","");
            logger.info("二次返回的HTML:"+httpResponseNew.getDocument().text());
            Element stordIdEl = httpResponseNew.getDocument().selectFirst("input[id=storeId]");
            storeId = stordIdEl.val();
        }else{
            storeId = priceElement.val();
        }

        //https://www.shouyinbei.net/wap/merchant/h5pay?code=&auth_code=&userAuthCode=&merchantCode=M800202205191d87ef&userAppId=93816&qrNo=null&payType=ZFBZF&cokus=2088002606948690&province=%E7%A6%8F%E5%BB%BA%E7%9C%81




        dataMap = new HashMap();
        dataMap.put("storeId",storeId);
        dataMap.put("merchantCode",merchantCode);
        dataMap.put("userId",orderInfo.getAliUserId());
        dataMap.put("userAppId",cookieObj.getString("userId"));
        dataMap.put("payWay",payType);
        dataMap.put("comsumeMoney", MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        url = "https://www.shouyinbei.net/wap/merchant/tradePay";
        logger.info("下单URL："+url);
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("请求参数："+preStr);

        headerMap.put("Referer","https://www.shouyinbei.net/wap/merchant/h5pay?auth_code="+orderInfo.getAliAuthCode()+"&userAppId="+cookieObj.getString("userId"));

//        HttpResponse payHttpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"SYB下单",proxyIp);
        String payHttpResponse = "";
//        if(proxyIp==null){
//            payHttpResponse = HttpUtils.sendPostRequest(url,preStr,headerMap);
//        }else{
//            payHttpResponse = HttpUtils.sendPostRequestByProxyIp(url,preStr,headerMap,proxyIp);
//        }
        payHttpResponse = HttpUtils.sendPostRequest(url,preStr,headerMap);
        logger.info("syb请求返回的:"+payHttpResponse);

        JSONObject payInforesultObj = JSONObject.parseObject(payHttpResponse);
        if(payInforesultObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            logger.info("========SYB修改收款账号为不可用===============");
            userRecipientInfo.setChannelDisabled(1);
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONObject jspay_info = payInforesultObj.getJSONObject("data");
        String tradeNO = jspay_info.getString("source");
//        JSONObject payInfoObj = new JSONObject();
//        payInfoObj.put("appid",payInforesultObj.getString("appid"));
//        payInfoObj.put("merchant_id",payInforesultObj.getString("merchant_id"));
//        payInfoObj.put("qrcode",qrcode_);
//        payInfoObj.put("order_id",payInforesultObj.getString("order_id"));
//        payInfoObj.put("notify_key",payInforesultObj.getString("notify_key"));
//        payInfoObj.put("third_order_id",payInforesultObj.getString("third_order_id"));
//        orderInfo.setQrcodeTxt(payInfoObj.toJSONString());
//        orderInfoDao.update(orderInfo);
        orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
        orderInfo.setQrcodeTxt(cookieObj.toJSONString());
        orderInfoService.updateTOrderInfo(orderInfo);
        jsonObject.put("payUrl",tradeNO);
        jsonObject.put("orderNo",jspay_info.getString("orderNumber"));
        jsonObject.put("code","200");
        return jsonObject;
    }


    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);


        String proxyIp =orderInfo.getProxyIp();

        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.22(0x18001627) NetType/4G Language/zh_CN");


        logger.info("qrcode："+cookieObj.getString("userId"));

        String url ="https://shop.shouyinbei.net/app/wxapp.php?i=1&v=undefined&m=we7_wmall&c=entry&do=mobile&ctrl=wmall&ac=store&op=paybill&ta=getNewStoreInfo&from=wxapp&state=we7sid-1f5947214065a723ec571946828f80ac&code_id="+cookieObj.getString("userId")+"&type=2&is_pay=1&sid=undefined";
        logger.info("收银台HTMLurl："+url);

        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","SYB",proxyIp);
        logger.info("返回的HTML:"+httpResponse.getDocument().text());
        JSONObject storeIdObj = JSONObject.parseObject(httpResponse.getDocument().text());

        String storeId = storeIdObj.getJSONObject("message").getString("store_id");
//        url ="https://shop.shouyinbei.net/app/wxapp.php?i=1&v=undefined&m=we7_wmall&c=entry&do=mobile&ctrl=wmall&ac=store&op=paybill&ta=index&from=wxapp&state=we7sid-1f5947214065a723ec571946828f80ac&sid="+storeId+"&total_fee="+MoneyUtil.fenToYuan(orderInfo.getMoney()+"")+"&no_discount_part=0&discount_amt=0&couponId=false&note=&is_pay=1&province=";
//        logger.info("收银台HTMLurl："+url);
//
//        httpResponse = HttpUtils.httpFormGet(url,headerMap,"","SYB",proxyIp);
//        logger.info("预生成的微信订单号:"+httpResponse.getDocument().text());
//        JSONObject perOrderObj = JSONObject.parseObject(httpResponse.getDocument().text());
//
//        String perOrderId = perOrderObj.getJSONObject("message").getString("message");
//        url = "https://shop.shouyinbei.net/app/wxapp.php?i=1&v=undefined&m=we7_wmall&c=entry&do=mobile&ctrl=system&ac=paycenter&op=pay&from=wxapp&state=we7sid-1f5947214065a723ec571946828f80ac&pay_type=new_wechat&order_type=paybill&id="+perOrderId+"&pay_type2=0&province=&city=&nickName=&avatar=&snNo=&order_source=&note=";
//        httpResponse = HttpUtils.httpFormGet(url,headerMap,"","SYB",proxyIp);
//        JSONObject payOrderObj = JSONObject.parseObject(httpResponse.getDocument().text());
//        String payAppId = payOrderObj.getJSONObject("message").getJSONObject("message").toJSONString();


        dataMap = new HashMap();
        dataMap.put("storeId",storeId);
        dataMap.put("merchantCode",cookieObj.getString("merchantCode"));
        dataMap.put("userId",orderInfo.getAliUserId());
        dataMap.put("userAppId",cookieObj.getString("userId"));
        dataMap.put("payWay","WXZF");
        dataMap.put("comsumeMoney", MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        url = "https://www.shouyinbei.net/wap/merchant/tradePay";
        logger.info("下单URL："+url);
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("请求参数："+preStr);

        //headerMap.put("Referer","https://www.shouyinbei.net/wap/merchant/h5pay?auth_code="+orderInfo.getAliAuthCode()+"&userAppId="+cookieObj.getString("userId"));

//        HttpResponse payHttpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"SYB下单",proxyIp);
        String payHttpResponse = HttpUtils.sendPostRequestByProxyIp(url,preStr,headerMap,proxyIp);

        logger.info("syb请求返回的:"+payHttpResponse);

        JSONObject payInforesultObj = JSONObject.parseObject(payHttpResponse);
        if(payInforesultObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            return jsonObject;
        }
        JSONObject jspay_info = payInforesultObj.getJSONObject("data");
        String tradeNO = jspay_info.toJSONString();
//        JSONObject payInfoObj = new JSONObject();
//        payInfoObj.put("appid",payInforesultObj.getString("appid"));
//        payInfoObj.put("merchant_id",payInforesultObj.getString("merchant_id"));
//        payInfoObj.put("qrcode",qrcode_);
//        payInfoObj.put("order_id",payInforesultObj.getString("order_id"));
//        payInfoObj.put("notify_key",payInforesultObj.getString("notify_key"));
//        payInfoObj.put("third_order_id",payInforesultObj.getString("third_order_id"));
//        orderInfo.setQrcodeTxt(payInfoObj.toJSONString());
//        orderInfoDao.update(orderInfo);
        orderInfo.setQrcodeTxt(cookieObj.toJSONString());
        orderInfoService.updateTOrderInfo(orderInfo);
        jsonObject.put("payUrl",tradeNO);
        jsonObject.put("orderNo",jspay_info.getString("orderNumber"));
        jsonObject.put("code","200");
        return jsonObject;
    }

    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }


}
